package com.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.mapper.UserMapper;
import com.app.model.FormModel;
import com.app.model.PersonModel;
import com.app.model.UserModel;
import com.app.service.UserService;
import com.app.util.*;
import com.app.vo.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description:用户实现类
 * @Author: N
 * @Date: 2022年11月24日 10点29分
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /***
     * 新增用户
     * @param model
     * @return
     */
    @Override
    public int insert(UserModel model) {

        return userMapper.insert(model);
    }

    /***
     * 修改用户
     * @param model
     * @return
     */
    @Override
    public int update(UserModel model) {
        return userMapper.updateById(model);
    }


    /***
     * 根据手机号查询
     * @param mobile
     * @return
     */
    @Override
    public UserModel getUserByMobile(String mobile) {
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", mobile);
        List<UserModel> userList = userMapper.selectByMap(map);
        if (userList.isEmpty()) {
            return null;
        } else {
            return userList.get(0);
        }
    }


    /***
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public UserModel getUserById(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public Object doLogin(String code, String code1) {

        Map<String, Object> body = WXLonginUtil.getPhone(code);
        String openid = getOpenid(code1);

        Map<String, String> phoneInfoMap = WXLonginUtil.mapStringToMap(String.valueOf(body.get("phone_info")));
        String mobile = phoneInfoMap.get("phoneNumber");
//            String openId = phoneInfoMap.get("open_id");

        UserModel user = getUserByMobile(mobile);
        LoginVo loginVo = new LoginVo();
        //判断是否为首次登录
        if (user == null) {
            user = new UserModel();
            user.setMobile(mobile);
            user.setUserName("用户" + getUUID(5));
            user.setRealName("用户");
            user.setFaceUrl("https://ssp.yumentv.cn/api/file/moren.jpg");
//            user.setFaceUrl("C:/Users/Adminstrator/Desktop/moren.jpg");
            //记得加线上地址
            user.setOpenId(openid);//openid
            user.setCrtTime(CommonHelp.getNowTimestamp());
            insert(user);
            String token = TokenUtils.sign(String.valueOf(user.getId()));

            loginVo.setToken(token);
            loginVo.setUser(user);
            return loginVo;
        }
        UserModel userModel = new UserModel();
        userModel.setOpenId(openid);
        userModel.setFaceUrl(user.getFaceUrl());
        userModel.setRealName(user.getRealName());
        userModel.setUserName(user.getUserName());
        userModel.setMobile(user.getMobile());
        userModel.setId(user.getId());
        update(userModel);
        String token = TokenUtils.sign(String.valueOf(user.getId()));
        loginVo.setToken(token);
        loginVo.setUser(userModel);
        return loginVo;
    }

    @Override
    public Integer getModelTodayCount() {
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(CommonHelp.getNowTimestamp());
        queryWrapper.like("crt_time", time);
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer getModelYesterdayCount() {
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        Date date = new Date(CommonHelp.getNowTimestamp().getTime());
        Date yDate = DateUtil.addDays(date, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(yDate);
        queryWrapper.like("crt_time", time);
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public Integer getModelCount() {
        return userMapper.selectCount(null);
    }

    @Override
    public int getModelCountByTime(String crtTime) {
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.apply("TO_DAYS(crt_time) = TO_DAYS('" + crtTime + "')");
        return userMapper.selectCount(queryWrapper);
    }

    @Override
    public Page<UserModel> getUserPage(UserModel model) {
        QueryWrapper<UserModel> queryWrapper = new QueryWrapper<>();
        if (StringTool.isNotEmpty(model.getKeyWord())) {
            queryWrapper.like("user_name", model.getKeyWord()).or().like("mobile", model.getKeyWord());
        }
        Page<UserModel> pages = new Page<>();
        pages.setCurrent(model.getPage());
        pages.setSize(model.getLimit());
        Page<UserModel> modelPage = userMapper.selectPage(pages, queryWrapper);
        return modelPage;
    }

    @Override
    public UserModel wxLogin(String code) {
        //获取openid
        String openid = getOpenid(code);
        UserModel model = new UserModel();
        model.setOpenId(openid);
        return model;
    }

    @Override
    public List<UserModel> whiteList() {
        return userMapper.whiteList();
    }

    @Override
    public List<UserModel> selectList() {
        return userMapper.selectList(null);
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String getUUID(int len) {
        if (0 >= len) {
            return null;
        }

        String uuid = getUUID();
        System.out.println(uuid);
        StringBuffer str = new StringBuffer();

        for (int i = 0; i < len; i++) {
            str.append(uuid.charAt(i));
        }

        return str.toString();
    }

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    private String getOpenid(String code) {
        //请求封装参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", WXConstant.APPID);
        map.put("secret", WXConstant.SECRET);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }

//    public static void main(String[] args) {
//        System.out.println(getUUID(5));
//    }
}
